<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="商户名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入商户名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:shop:add']"
          >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:shop:edit']"
          >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:shop:remove']"
          >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:shop:export']"
          >导出
        </el-button>
      </el-col>
    </el-row>

    <el-table
      v-loading="loading"
      :data="shopList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="id" />
      <el-table-column label="商户名称" align="center">
        <template slot-scope="scope">
          <div class="user-info">
            <div class="info" style="display: flex; flex-direction: column">
              <span v-text="'昵称：' + scope.row.name" />
              <span v-text="'系统用户编号：' + scope.row.userId" />
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="联系方式" align="center">
        <template slot-scope="scope">
          <div class="contactInfo">
            <div>
              所在地区：{{ scope.row.province }}-{{ scope.row.city }}-{{
                scope.row.area
              }}
            </div>
            <div>所在地址：{{ scope.row.address }}</div>
            <div>联系人姓名：{{ scope.row.contactName }}</div>
            <div>联系人电话：{{ scope.row.contactPhone }}</div>
            <div>
              营业时间：{{ scope.row.businessTime }}-{{ scope.row.closingTime }}
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="配送范围" align="center" prop="distScope" />
      <el-table-column label="商户金额" align="center" prop="balance" />
      <el-table-column label="商户状态" align="center">
        <template slot-scope="scope">
          <el-tag type="warning" v-if="scope.row.openState == 1">禁用</el-tag>
          <el-tag type="success" v-if="scope.row.openState == 0">正常</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>

      <el-table-column label="扫码查看" align="center" prop="qrcode">
        <template slot-scope="scope">
          <img
            :src="'data:image/png;base64,' + scope.row.qrcodeImg"
            style="width: 100px; height: 100px"
          />
        </template>
      </el-table-column>

      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        fixed="right"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:shop:edit']"
            >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:shop:remove']"
            >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改商户信息对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="1000px"
      append-to-body
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-tabs
          v-model="activeTabs"
          tab-position="left"
          @tab-click="switchTable"
        >
          <el-tab-pane label="店铺位置" name="1">
            <el-row :gutter="24">
              <el-col :span="24">
                <el-form-item
                  label="位置区域"
                  prop="province"
                  class="distpicker-select"
                >
                  <v-distpicker
                    :province="form.province"
                    :city="form.city"
                    :area="form.area"
                    @selected="onDistpicker"
                  ></v-distpicker>
                </el-form-item>
                <el-form-item
                  label="位置信息"
                  class="location"
                >
                  <web-map
                    ref="webMap"
                    :lng.sync="form.lng"
                    :lat.sync="form.lat"
                    :address.sync="form.address"
                    :scope.sync="form.distScope"
                  ></web-map>
                </el-form-item>
                <el-form-item label="配送范围(km)" prop="distScope">
                  <el-input-number
                    v-model="form.distScope"
                    @change="handleChange"
                    controls-position="right"
                    :min="1"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>
          <el-tab-pane label="店铺信息" name="2">
            <el-row :gutter="24">
              <el-col :span="15">
                <el-form-item label="商户名称" prop="name">
                  <el-input v-model="form.name" placeholder="请输入商户名称" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="24">
              <el-col :span="18">
                <el-form-item label="营业时间" prop="businessTime">
                  <el-time-select
                    placeholder="起始时间"
                    v-model="form.businessTime"
                    :disabled="checked"
                    :picker-options="{
                      start: '00:00',
                      step: '00:15',
                      end: '23:00',
                    }"
                  >
                  </el-time-select>
                  -
                  <el-time-select
                    placeholder="结束时间"
                    v-model="form.closingTime"
                    :disabled="checked"
                    :picker-options="{
                      start: '00:01',
                      step: '00:15',
                      end: '23:59',
                    }"
                  >
                  </el-time-select>
                  <el-checkbox v-model="checked" @change="handleCheckBox"
                    >全日</el-checkbox
                  >
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="24">
              <el-form-item label="店铺图片" prop="storeImgs">
                <el-upload
                  :action="commonUploadApi"
                  :accept="'.png,.jpg'"
                  list-type="picture-card"
                  :on-preview="handlePictureCardPreview"
                  :on-remove="handleRemove"
                  :on-success="uploadSuccess"
                  :headers="headers"
                  :limit="imgLimitUpload"
                  :file-list="fileList"
                >
                  <i class="el-icon-plus"></i>
                </el-upload>
                <el-dialog :visible.sync="dialogVisible">
                  <img width="100%" :src="dialogImageUrl" alt="" />
                </el-dialog>
              </el-form-item>
            </el-row>
            <el-row :gutter="24">
              <el-form-item label="店铺资质" prop="storePapers">
                <el-upload
                  :action="commonUploadApi"
                  :accept="'.png,.jpg'"
                  list-type="picture-card"
                  :on-preview="handlePictureCardPreview1"
                  :on-remove="handleRemove1"
                  :on-success="uploadSuccess1"
                  :headers="headers"
                  :limit="imgLimitUpload"
                  :file-list="fileList1"
                >
                  <i class="el-icon-plus"></i>
                </el-upload>
              </el-form-item>
            </el-row>
          </el-tab-pane>
          <el-tab-pane label="账户信息" name="3">
            <el-row :gutter="24" v-if="form.id == undefined">
              <el-col :span="12">
                <el-form-item label="登录账户" prop="userName">
                  <el-input
                    v-model="form.userName"
                    placeholder="请输入登录账户"
                  />
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="登录密码" prop="password">
                  <el-input
                    type="password"
                    v-model="form.password"
                    placeholder="请输入登录密码"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="24">
              <el-col :span="12">
                <el-form-item label="联系人姓名" prop="contactName">
                  <el-input
                    v-model="form.contactName"
                    placeholder="请输入联系人姓名"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="联系人电话" prop="contactPhone">
                  <el-input
                    v-model="form.contactPhone"
                    placeholder="请输入联系人电话"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>
        </el-tabs>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" v-if="active == 2"
          >提 交</el-button
        >
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listShop,
  getShop,
  delShop,
  addShop,
  updateShop,
  exportShop,
} from "@/api/system/shop";
import VDistpicker from "v-distpicker";
import WebMap from "@/components/WebMap"; // svg component
import { mapGetters } from "vuex";
import { getToken } from "@/utils/auth";
var map, placeSearch;
export default {
  components: { VDistpicker, WebMap },
  name: "Shop",
  data() {
    return {
      base: process.env.VUE_APP_BASE_API,
      center: [121.329402, 31.228667],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 商户信息表格数据
      shopList: [],
      //限制上传个数
      imgLimitUpload: 5,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      dialogImageUrl: "",
      dialogVisible: false,
      fileList: [],
      fileList1: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: undefined,
        province: undefined,
        city: undefined,
        area: undefined,
        address: undefined,
        lng: undefined,
        lat: undefined,
        contactName: undefined,
        contactPhone: undefined,
        businessTime: undefined,
        closingTime: undefined,
        distScope: undefined,
        storeImgs: undefined,
        storePapers: undefined,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: "商户名称不能为空", trigger: "blur" },
        ],
        province: [
          { required: true, message: "省名称不能为空", trigger: "blur" },
        ],
        city: [
          { required: true, message: "城市名称不能为空", trigger: "blur" },
        ],
        area: [
          { required: true, message: "区域名称不能为空", trigger: "blur" },
        ],
        address: [
          { required: true, message: "商户地址不能为空", trigger: "blur" },
        ],
        lng: [{ required: true, message: "商户经度不能为空", trigger: "blur" }],
        lat: [{ required: true, message: "商户纬度不能为空", trigger: "blur" }],
        contactName: [
          { required: true, message: "联系人姓名不能为空", trigger: "blur" },
        ],
        contactPhone: [
          {
            required: true,
            message: "联系人手机号码不能为空",
            trigger: "blur",
          },
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur",
          },
        ],
        businessTime: [
          { required: true, message: "营业时间不能为空", trigger: "blur" },
        ],
        closingTime: [
          { required: true, message: "下班时间不能为空", trigger: "blur" },
        ],
        distScope: [
          { required: true, message: "配送范围不能为空", trigger: "blur" },
        ],
        //后台登陆账号
        userName: [
          {
            required: true,
            message: "手机号码不能为空",
            trigger: "blur",
          },
        ],
        password: {
          required: true,
          min: 6,
          message: "密码最少6位",
        },
        storeImgs: [
          {
            required: true,
            message: "请上传店铺图片",
            trigger: "blur",
          },
        ],
        storePapers: [
          {
            required: true,
            message: "请上传店铺资质",
            trigger: "blur",
          },
        ],
      },
      search: "",
      placeSearch: null,
      loaded: false,
      activeTabs: "1",
      active: 0,
      checked: false,
      headers: { Authorization: "Bearer " + getToken() },
    };
  },
  computed: {
    ...mapGetters(["commonUploadApi"]),
  },
  created() {
    this.getList();
  },
  methods: {
    //+++++++++++++++++++++++++++++++++++++上传商品主图操作
    handleRemove(file, fileList) {
      this.form.storeImgs = undefined;
      fileList.forEach((item) => {
        if (this.form.storeImgs == undefined) {
          this.form.storeImgs = item.response.url;
        } else {
          this.form.storeImgs = this.form.storeImgs + "," + item.response.url;
        }
      });
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    //多图上传成功后的钩子
    uploadSuccess(response, file, fileList) {
      if (this.form.storeImgs == undefined) {
        this.form.storeImgs = response.url;
      } else {
        this.form.storeImgs = this.form.storeImgs + "," + response.url;
      }
      this.$refs.form.clearValidate("storeImgs");
    },
    //资质图集
    handleRemove1(file, fileList) {
      this.form.storePapers = undefined;
      fileList.forEach((item) => {
        if (this.form.storePapers == undefined) {
          this.form.storePapers = item.response.url;
        } else {
          this.form.storePapers =
            this.form.storePapers + "," + item.response.url;
        }
      });
    },
    handlePictureCardPreview1(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    //多图上传成功后的钩子
    uploadSuccess1(response, file, fileList) {
      if (this.form.storePapers == undefined) {
        this.form.storePapers = response.url;
      } else {
        this.form.storePapers = this.form.storePapers + "," + response.url;
      }
      this.$refs.form.clearValidate("storePapers");
    },
    switchTable: function (tab, event) {
      this.active = this.activeTabs - 1;
    },
    handleCheckBox() {
      if (this.checked == true) {
        this.form.businessTime = "00:00";
        this.form.closingTime = "23:59";
      } else {
        this.form.businessTime = "";
        this.form.closingTime = "";
      }
      this.$forceUpdate();
    },
    /** 查询商户信息列表 */
    getList() {
      this.loading = true;
      listShop(this.queryParams).then((response) => {
        this.shopList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        name: undefined,
        province: "安徽省",
        city: "合肥市",
        area: "蜀山区",
        address: "",
        lng: "116.397428",
        lat: "39.90923",
        contactName: undefined,
        contactPhone: undefined,
        businessTime: undefined,
        closingTime: undefined,
        distScope: 1,
        storeImgs: undefined,
        storePapers: undefined,
        userName: undefined,
        password: undefined,
      };
      let that = this;
      this.checked = false;
      this.activeTabs = "1";
      setTimeout(function () {
        that.$refs.webMap.init(that.form.lng, that.form.lat);
      }, 1000);
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.fileList = [];
      this.fileList1 = [];
      this.open = true;
      this.title = "添加商户信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      let that = this;
      getShop(id).then((response) => {
        this.form = response.data;
        //处理图片
        //图片回显
        this.fileList = [];
        this.fileList1 = [];
        var arr = this.form.storeImgs.split(",");
        if (arr.length > 0) {
          arr.forEach((val) => {
            var data = {
              url: val,
              response: {
                url: val,
              },
            };
            this.fileList.push(data);
          });
        }
        var arr1 = this.form.storePapers.split(",");
        if (arr1.length > 0) {
          arr1.forEach((val) => {
            var data = {
              url: val,
              response: {
                url: val,
              },
            };
            this.fileList1.push(data);
          });
        }
        this.open = true;
        this.title = "修改商户信息";
        setTimeout(function () {
          that.$refs.webMap.init(that.form.lng, that.form.lat);
        }, 1000);
      });
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (
            this.form.address == "" ||
            this.form.lng == "" ||
            this.form.lat == ""
          ) {
            this.msgError("请输入位置信息");
            return;
          }
          if (this.form.id != undefined) {
            updateShop(this.form).then((response) => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addShop(this.form).then((response) => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm(
        '是否确认删除商户信息编号为"' + ids + '"的数据项?',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(function () {
          return delShop(ids);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
        .catch(function () {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm("是否确认导出所有商户信息数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return exportShop(queryParams);
        })
        .then((response) => {
          this.download(response.data);
        })
        .catch(function () {});
    },
    onDistpicker(data) {
      try {
        this.form.province = data.province.value;
        this.form.city = data.city.value;
        this.form.area = data.area.value;
        this.searchOption.city = data.city.value;
      } catch (e) {
        console.log("获取信息异常：" + e);
      }
    },
    //改变区域范围刷新 搜索范围
    handleChange() {
      this.$refs.webMap.setRadius(this.form.distScope);
    },
    onSearchResult(pois) {
      let poi = pois[0];
      this.amapConfig.markers = [];
      this.amapConfig.center = [poi.lng, poi.lat];
      this.amapConfig.markers.push([poi.lng, poi.lat]);
    },
    searchAddress() {
      placeSearch.search(this.address);
    },
    //上传图片
    handleSuccess(response, file, fileList) {
      this.form.storeImgs = response.url;
    },
    handleSuccessPapers(response, file, fileList) {
      this.form.storePapers = response.url;
    },
  },
  mounted() {},
};
</script>
<style>
.distpicker-address-wrapper select {
  width: 100px !important;
  height: 100%;
}
</style>
<style lang="scss" scoped>
.user-info {
  display: flex;
  justify-content: center;
  align-items: center;
}

.user-info .avatar {
  width: 50px;
  height: 50px;
}

.user-info .info {
  width: 100px;
  margin-left: 5px;
  margin-top: 5px;
  font-size: 12px;
}

.distpicker-select {
  .distpicker-address-wrapper {
    width: 320px;
  }

  .search {
    display: flex;
    margin-bottom: 10px;
  }

  .search #ipt {
    width: 100%;
    height: 100%;
    margin-top: 2px;
  }

  .amap-box {
    width: 100%;
    height: 400px !important;
    margin: 0 auto;
  }

  .search-box {
    box-shadow: initial;
    width: 550px;
    margin-top: 3px;
  }
}

#panel {
  position: absolute;
  background-color: white;
  max-height: 90%;
  overflow-y: auto;
  top: 80px;
  right: 10px;
  width: 280px;
}
</style>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
